<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- //!工具条组件 -->
      <PageTools :text="`当前共有${total}条记录`">
        <el-button
          size="small"
          type="danger"
          :disabled="!checkBtnPermission('employee_export')"
          @click="exportFn1"
        >
          普通Excel导出
        </el-button>
        <el-button
          size="small"
          type="warning"
          :disabled="!checkBtnPermission('employee_export')"
          @click="exportFn2"
        >
          复杂Excel导出
        </el-button>
        <el-button
          size="small"
          type="success"
          :disabled="!checkBtnPermission('employee_import')"
          @click="$router.push('/import?type=user')"
        >
          excel导入
        </el-button>
        <el-button
          size="small"
          type="primary"
          :disabled="!checkBtnPermission('employee_add')"
          @click="$refs.addEmp.dialogShow = true"
        >
          新增员工
        </el-button>
      </PageTools>
      <!-- //!渲染数据 -->
      <el-card>
        <el-table :data="tableData" border @selection-change="selectionChange">
          <el-table-column type="selection" sortable="" />
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" sortable="">
            <template slot-scope="scope">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="scope.row.staffPhoto"
                alt=""
                style="height: 60px"
                @click="showCode(scope.row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="formatterFn"
            sortable=""
          >
            <!-- <template slot-scope="scope">
              {{ scope.row.formOfEmployment }}
              <span v-if="scope.row.formOfEmployment === 1">正式</span>
              <span v-else-if="scope.row.formOfEmployment === 2">非正式</span>
              <span v-else>其他</span>
            </template> -->
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="" sortable="" />
          <el-table-column
            label="操作"
            prop="right"
            sortable=""
            fixed="right"
            width="280"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail/' + scope.row.id)"
              >
                查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button
                type="text"
                size="small"
                @click="openRole(scope.row.id)"
              >
                角色
              </el-button>
              <el-button type="text" size="small" @click="delRow(scope.row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <br />
        <br />
        <el-pagination
          :current-page.sync="queryData.page"
          :page-size="queryData.size"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          :total="total"
          @size-change="sizeChange"
          @current-change="pageChange"
        />
      </el-card>
      <!-- //!新增弹框 -->
      <addEmployees ref="addEmp" />
      <!-- //!图片二维码弹框 -->
      <el-dialog title="预览二维码" :visible.sync="dialogCodeShow">
        <canvas id="canvas" style="display: block; margin: 0 auto"></canvas>
      </el-dialog>
      <!-- //!设置角色弹框 -->
      <setRole ref="setRole" />
    </div>
  </div>
</template>

<script>
import setRole from '@/views/employees/components/setRole'
import QRCode from 'qrcode'
import addEmployees from '@/views/employees/components/addEmployees'
import employeesEnum from '@/api/constant/employees'
import { getEmployeesListApi, delEmployeesApi } from '@/api/employees'
import { formatDate } from '@/filters'
export default {
  name: 'Employees',
  components: { addEmployees, setRole },
  data() {
    return {
      tableData: [],
      queryData: {
        page: 1,
        size: 10
      },
      total: 0,
      checkTableData: [],
      dialogCodeShow: false
    }
  },
  created() {
    this.initData()
  },
  methods: {
    async initData() {
      const { rows, total } = await getEmployeesListApi(this.queryData)
      // console.log(res)
      console.log(rows)
      this.tableData = rows
      this.total = total
    },
    // 每页数量切换数量
    sizeChange(val) {
      this.queryData.size = val
      this.initData()
    },
    // 页码切换事件
    pageChange(val) {
      this.queryData.page = val
      this.initData()
    },
    // 对聘用列格式化
    formatterFn(row, column, cellValue, index) {
      // row行数据，column列信息，cellValue单元格值，index行索引
      // 该函数，return内容则单元格显示什么内容
      const res = employeesEnum.hireType.find(
        (item) => item.id === cellValue * 1
      )
      return res ? res.value : '未知'
    },
    async delRow(id) {
      console.log(id)
      // 弹出确认框
      try {
        await this.$confirm('确认删除吗？')
      } catch (e) {
        return console.log(e)
      }
      // 发送请求
      await delEmployeesApi(id)
      // 提示成功
      this.$message.success('删除成功')
      // !边缘问题
      if (this.queryData.page > 1 && this.tableData.length === 1) {
        this.queryData.page--
      }
      // 列表更新
      this.initData()
    },
    // 普通Excel导出
    exportFn1() {
      // 1.按需加载导出的Excel模块文件
      import('@/vendor/Export2Excel').then(async (excel) => {
        console.log(excel)
        // 2.获取需要导出的数据
        const { rows } = await getEmployeesListApi({
          page: 1,
          size: 100000000
        })
        // 3.整理数据过程
        const res = this.generateData(rows)
        // 4.excel就是加载好的模块，进行调用方法导出
        excel.export_json_to_excel({
          header: res.headerKey, // 表头 必填
          data: res.bodyData, // 具体数据 必填
          filename: '员工数据', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 整理数据
    generateData(data) {
      console.log(data)
      // 现有数据
      // [
      // {username:'张三',mobile:'123',departmentName:'组织部'},
      // {username:'888',mobile:'李四',departmentName:'宣传部'}
      // ]
      // 目标数据结构
      // [
      // ['123','张三','组织部'],
      // ['888','李四','宣传部']
      // ]
      const headers = {
        手机号: 'mobile',
        姓名: 'username',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const headerKey = Object.keys(headers)
      console.log(headerKey)
      const result = []
      data.forEach((item) => {
        console.log(item)
        console.log(Object.keys(headers))
        const row = []
        Object.keys(headers).forEach((val) => {
          console.log(val)
          console.log(headers[val])
          console.log(item[headers[val]])
          if (headers[val] === 'formOfEmployment') {
            const info = employeesEnum.hireType.find(
              (obj) => obj.id === item[headers[val]] * 1
            )
            row.push(info ? info.value : '未知')
          } else if (['timeOfEntry', 'correctionTime'].includes(headers[val])) {
            row.push(formatDate(item[headers[val]]))
          } else {
            row.push(item[headers[val]])
          }
        })
        result.push(row)
      })
      return { headerKey, bodyData: result }
    },
    selectionChange(val) {
      this.checkTableData = val
    },
    async exportFn2() {
      const excel = await import('@/vendor/Export2Excel')
      if (!this.checkTableData.length) {
        return this.$message.warning('请勾选数据')
      }

      const res = this.generateData(this.checkTableData)
      console.log(res)
      excel.export_json_to_excel({
        header: res.headerKey, // 表头 必填
        multiHeader: [['基本信息', '', '', '', '', '', '部门']],
        merges: ['A1:F1', 'G1:G2'],
        data: res.bodyData, // 具体数据 必填
        filename: '员工数据', // 非必填
        autoWidth: true, // 非必填
        bookType: 'xlsx' // 非必填
      })
    },
    // 显示二维码弹框
    showCode(url) {
      if (!url) return
      this.dialogCodeShow = true
      this.$nextTick(() => {
        var canvas = document.getElementById('canvas')
        QRCode.toCanvas(canvas, url, function (error) {
          if (error) console.log(error)
          console.log('success!')
        })
      })
    },
    async openRole(id) {
      console.log(id)
      // 获取所有角色
      await this.$refs.setRole.getAllRoleList()
      // 获取当前员工的详细信息
      await this.$refs.setRole.getCurrentRole(id)
      // 打开弹框
      this.$refs.setRole.dialogShow = true
    }
  }
}
</script>

<style></style>
